# -*- coding: utf-8 -*-
"""
kmearn对地图上的地点进行聚类
"""

import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

filepath = './/data//places.txt'

with open(filepath) as f:
    places = f.read().strip().split('\n')

places = [i.split('	') for i in places]
places = [[i[0], float(i[-2]), float(i[-1])]for i in places]
X = np.array([np.array(i[1:]) for i in places])

K=range(1,10)
meandistortions=[]

for k in K:
    kmeans=KMeans(n_clusters=k)
    kmeans.fit(X)
    meandistortions.append(sum(np.min(
            cdist(X,kmeans.cluster_centers_,
                 'euclidean'),axis=1))/X.shape[0])

plt.plot(K,meandistortions,'bx-')
plt.xlabel('k')
plt.ylabel(u'平均畸变程度')
plt.title(u'用肘部法则来确定最佳的K值')

# 最佳k值为3(曲率最高)
kmeans=KMeans(n_clusters=3)
kmeans.fit(X)
# 获取聚类标签
label_pred = kmeans.labels_
print(label_pred)

